package com.objk.admin.security.component;

import com.objk.admin.security.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class SecurityHolderUtils {

    public UserVo getCurrentUser() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (null != context && context.getAuthentication() != null) {
            Authentication authentication = context.getAuthentication();
            Object principal = authentication.getPrincipal();
            if (UserVo.class.isInstance(principal)) {
                UserVo userVo = (UserVo) authentication.getPrincipal();
                userVo.setPassword(StringUtils.EMPTY);
                return userVo;
            }
        }
        return null;
    }

    public Integer getUserId() {
        UserVo userVo = getCurrentUser();
        if (userVo != null && userVo.getUserId() != null) {
            return userVo.getUserId();
        }
        return null;
    }
}
